<template>
    <div class="video-uploader">
      <el-upload
        ref="uploadRef"
        class="uploader"
        :action="uploadUrl"
        :accept="acceptTypes"
        :limit="1"
        :show-file-list="true"
        :auto-upload="true"
        :before-upload="handleBeforeUpload"
        :on-progress="handleProgress"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-exceed="handleExceed"
      >
        <!-- 上传触发器 -->
        <template #trigger>
          <el-button type="primary">选择视频文件</el-button>
        </template>
  
        <!-- 文件列表插槽 (可选，如果 show-file-list=true) -->
        <!-- 你可以在这里自定义文件列表项的显示 -->
  
        <!-- 提示信息 -->
        <template #tip>
          <div class="el-upload__tip">
            只能上传 {{ acceptTypes }} 格式文件，且不超过 {{ maxFileSizeMB }}MB
          </div>
        </template>
      </el-upload>
  
      <!-- 上传进度条 -->
      <div v-if="showProgress" class="progress-container">
        <el-progress :percentage="uploadProgress" :stroke-width="10" status="success" />
      </div>
  
      <!-- 视频预览 -->
      <div v-if="videoUrl" class="preview-container">
        <h3>视频预览:</h3>
        <video controls width="400" :src="videoUrl">
          您的浏览器不支持 video 标签。
        </video>
        <div>
          <el-button type="primary" link @click="copyUrl">复制视频地址</el-button>
        </div>
      </div>
  
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import type { UploadInstance, UploadProps, UploadRawFile, UploadFile, UploadFiles } from 'element-plus';

   // 子传父
   const emit = defineEmits<{
        (e: 'success', url: string): void;
    }>();
  const url = import.meta.env.VITE_APP_BASE_URL + '/api/upload/video'
  // --- 配置项 ---
  // 后端接收上传文件的地址 (!!! 必须替换为你的真实后端地址 !!!)
  const uploadUrl = ref<string>(url);
  // 允许上传的文件类型
  const acceptTypes = ref<string>('video/mp4, video/mov, video/avi, video/wmv, video/mkv, video/webm');
  // 最大文件大小 (MB)
  const maxFileSizeMB = ref<number>(500);
  
  // --- 组件引用和状态 ---
  const uploadRef = ref<UploadInstance>();
  const uploadProgress = ref<number>(0); // 上传进度百分比
  const showProgress = ref<boolean>(false); // 是否显示进度条
  const videoUrl = ref<string | null>(null); // 上传成功后的视频URL
  
  // --- 上传处理函数 ---
  
  // 上传前校验
  const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {
    // 检查文件类型
    const fileType = rawFile.type;
    if (!acceptTypes.value.includes(fileType)) {
      ElMessage.error(`文件格式不支持！请上传 ${acceptTypes.value} 格式的视频。`);
      return false;
    }
  
    // 检查文件大小
    const fileSizeMB = rawFile.size / 1024 / 1024;
    if (fileSizeMB > maxFileSizeMB.value) {
      ElMessage.error(`文件大小不能超过 ${maxFileSizeMB.value}MB！`);
      return false;
    }
  
    // 校验通过，准备开始上传
    showProgress.value = true;
    uploadProgress.value = 0;
    videoUrl.value = null; // 清除旧的预览
    return true;
  };
  
  // 上传进度
  const handleProgress: UploadProps['onProgress'] = (event, uploadFile, uploadFiles) => {
    // event.percent 可能为 undefined 或 0，做个保护
    uploadProgress.value = Math.floor(event.percent || 0);
  };
  
  // 上传成功
  const handleSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.log('Upload Success:', response, uploadFile);
    showProgress.value = false;
    uploadProgress.value = 100; // 确保进度条显示完成 (虽然很快会消失)
  
    // !!! 关键: 从后端响应中获取视频 URL !!!
    // !!! 假设后端返回 { "url": "..." } 格式 !!!
    if (response && response.data && response.data.uri) {
      videoUrl.value = response.data.uri;
        emit('success', response.data.uri)
      ElMessage.success('视频上传成功！');
    } else {
      // 如果后端响应格式不符合预期
      console.error('后端响应缺少 url 字段:', response);
      ElMessage.error('上传成功，但无法获取视频预览地址。请检查后端响应格式。');
      // 清理文件列表，避免显示错误的文件状态
       if (uploadRef.value) {
        uploadRef.value.clearFiles(); // 清除文件列表
      }
    }
  };
  
  // 上传失败
  const handleError: UploadProps['onError'] = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    console.error('Upload Error:', error);
    showProgress.value = false;
    uploadProgress.value = 0;
    videoUrl.value = null;
    ElMessage.error(`视频上传失败: ${error.message || '未知错误'}`);
    // 清理文件列表，避免显示错误的文件状态
    if (uploadRef.value) {
        uploadRef.value.clearFiles(['fail']); // 清除失败的文件
    }
  };
  
  // 超出文件数量限制
  const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(
      `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
        files.length + uploadFiles.length
      } 个文件`
    );
  };
  
  // --- 预览相关 ---
  const copyUrl = async () => {
    if (!videoUrl.value) return;
    try {
      await navigator.clipboard.writeText(videoUrl.value);
      ElMessage.success('视频地址已复制到剪贴板！');
    } catch (err) {
      console.error('Failed to copy: ', err);
      ElMessage.error('复制失败，请手动复制。');
    }
  };
  

 
  </script>
  
  <style scoped>
  .video-uploader {
    width: 500px; /* 或者你希望的宽度 */
    padding: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .uploader {
    margin-bottom: 20px;
  }
  
  .progress-container {
    margin-top: 15px;
    margin-bottom: 15px;
  }
  
  .preview-container {
    margin-top: 20px;
    border-top: 1px dashed #dcdfe6;
    padding-top: 15px;
  }
  
  .preview-container h3 {
    margin-bottom: 10px;
    font-size: 16px;
  }
  
  .preview-container video {
    max-width: 100%; /* 确保视频不会超出容器 */
    display: block;
    margin-bottom: 10px;
  }
  
  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 7px;
  }
  </style>